<template>
  <div class="login">
    <h2>{{ $t('message.login') }}</h2>
    <form @submit.prevent="login">
      <div class="form-group">
        <label for="username">{{ $t('message.username') }}</label>
        <input 
          type="text" 
          id="username" 
          v-model="username" 
          required 
          :placeholder="$t('message.pleaseEnterUsername')"
        />
      </div>
      <div class="form-group">
        <label for="password">{{ $t('message.password') }}</label>
        <input 
          type="password" 
          id="password" 
          v-model="password" 
          required 
          :placeholder="$t('message.pleaseEnterPassword')"
        />
      </div>
      <button type="submit" :disabled="loading">
        {{ loading ? $t('message.loggingIn') : $t('message.login') }}
      </button>
    </form>
    <p>{{ $t('message.dontHaveAccount') }}<router-link to="/register">{{ $t('message.registerHere') }}</router-link></p>
  </div>
</template>

<script>
import { useAuthStore } from '@/stores/auth'
import { useRouter } from 'vue-router'

export default {
  name: 'LoginView',
  setup() {
    const authStore = useAuthStore()
    const router = useRouter()
    
    return {
      authStore,
      router
    }
  },
  data() {
    return {
      username: '',
      password: '',
      loading: false
    }
  },
  methods: {
    async login() {
      this.loading = true
      try {
        await this.authStore.login(this.username, this.password)
        
        // 根据用户角色决定跳转页面
        if (this.authStore.user?.roleId === 'ADMIN') {
          await this.router.push('/admin')
        } else if (this.authStore.user?.roleId === 'TEACHER') {
          await this.router.push('/teacher')
        } else if (this.authStore.user?.roleId === 'PARENT') {
          await this.router.push('/parent')
        } else if (this.authStore.user?.roleId === 'ASSISTANT') {
          await this.router.push('/assistant')
        } else {
          await this.router.push('/')
        }
      } catch (error) {
        alert(this.$t('message.loginFailed') + ': ' + error.message)
      } finally {
        this.loading = false
      }
    }
  }
}
</script>

<style scoped>
.login {
  max-width: 400px;
  margin: 2rem auto;
  padding: 2rem;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.form-group {
  margin-bottom: 1rem;
  text-align: left;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
}

.form-group input {
  width: 100%;
  padding: 0.5rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  box-sizing: border-box;
}

button {
  width: 100%;
  padding: 0.75rem;
  background-color: #3498db;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

button:disabled {
  background-color: #bdc3c7;
  cursor: not-allowed;
}
</style>